package com.sy.simpleegg.ui.popupwindow

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.AppItemAdapter
import com.sy.simpleegg.ext.logFile

class CustomPopupWindow private constructor(builder: Builder) : PopupWindow(builder.context) {

    private var rvItem: RecyclerView? = null
    private var appAdapter: AppItemAdapter? = null

    private var onClickListener: OnClickListener? = null

    private var countDownTimer: CountDownTimer? = null

    init {
        builder.view!!.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        contentView = builder.view
        height =
            if (builder.height == 0) ViewGroup.LayoutParams.WRAP_CONTENT else builder.height
        width =
            if (builder.width == 0) ViewGroup.LayoutParams.WRAP_CONTENT else builder.width
        if (builder.cancelTouchout) {
            setBackgroundDrawable(ColorDrawable(0x00000000)) //设置透明背景
            isOutsideTouchable = builder.cancelTouchout //设置outside可点击
        }
        isFocusable = builder.isFocusable
        isTouchable = builder.isTouchable
        if (builder.animStyle != 0) {
            animationStyle = builder.animStyle
        }

        onClickListener = builder.onClickListener

        initData(builder.datas)
    }

    private fun initData(datas: MutableList<String>?){
        if (datas.isNullOrEmpty()){
            return
        }
        rvItem = contentView.findViewById(R.id.rv_item)
        rvItem?.layoutManager = LinearLayoutManager(contentView.context)
        appAdapter = AppItemAdapter(datas, object : AppItemAdapter.OnItemClickListener{
            override fun onItemClick(position: Int) {
                onClickListener?.onItemClick(position)
            }

        })
        rvItem?.adapter = appAdapter
    }

    class Builder(val context: Context) {
        var height = 0
        var width = 0
        var cancelTouchout = false
        var isFocusable = true
        var isTouchable = true
        var view: View? = null
        var animStyle = 0
        var datas: MutableList<String>? = null
        var onClickListener: OnClickListener? = null
        fun view(resView: Int): Builder {
            view = LayoutInflater.from(context).inflate(resView, null)
            return this
        }

        fun view(resVew: View?): Builder {
            view = resVew
            return this
        }

        fun heightpx(`val`: Int): Builder {
            height = `val`
            return this
        }

        fun widthpx(`val`: Int): Builder {
            width = `val`
            return this
        }

        fun heightdp(`val`: Int): Builder {
            height = dip2px(context, `val`.toFloat())
            return this
        }

        fun widthdp(`val`: Int): Builder {
            width = dip2px(context, `val`.toFloat())
            return this
        }

        fun heightDimenRes(dimenRes: Int): Builder {
            height = context.resources.getDimensionPixelOffset(dimenRes)
            return this
        }

        fun widthDimenRes(dimenRes: Int): Builder {
            width = context.resources.getDimensionPixelOffset(dimenRes)
            return this
        }

        fun cancelTouchout(`val`: Boolean): Builder {
            cancelTouchout = `val`
            return this
        }

        fun isFocusable(`val`: Boolean): Builder {
            isFocusable = `val`
            return this
        }

        fun isTouchable(`val`: Boolean): Builder {
            isTouchable = `val`
            return this
        }

        fun animStyle(`val`: Int): Builder {
            animStyle = `val`
            return this
        }

        fun addViewOnclick(viewRes: Int, listener: View.OnClickListener?): Builder {
            view!!.findViewById<View>(viewRes).setOnClickListener(listener)
            return this
        }

        fun onClick(listener: OnClickListener): Builder{
            onClickListener = listener
            return this
        }

        fun data(items: MutableList<String>): Builder{
            datas = items
            return this
        }

        fun build(): CustomPopupWindow {
            return CustomPopupWindow(this)
        }
    }

    override fun getWidth(): Int {
        return contentView.measuredWidth
    }

    override fun showAsDropDown(anchor: View?, xoff: Int, yoff: Int) {
        super.showAsDropDown(anchor, xoff, yoff)
        startCountDown()
    }

    override fun dismiss() {
        super.dismiss()
        countDownTimer?.cancel()
    }

    private fun startCountDown(){
        if (countDownTimer == null) {
            countDownTimer = object : CountDownTimer(10 * 1000L, 1000) {
                override fun onTick(millisUntilFinished: Long) {

                }

                override fun onFinish() {
                    logFile("${javaClass.simpleName} 倒计时结束，关闭popupwindow")
                    dismiss()
                }

            }
        }
        countDownTimer?.cancel()
        countDownTimer?.start()
    }

    companion object {
        fun dip2px(context: Context, dipValue: Float): Int {
            val scale = context.resources.displayMetrics.density
            return (dipValue * scale + 0.5f).toInt()
        }
    }

    interface OnClickListener{
        fun onItemClick(pos: Int)
    }
}